<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">











<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Javascript,">










<meta name="description" content="为什么要有Event Loop？因为Javascript设计之初就是一门单线程语言，因此为了实现主线程的不阻塞，Event Loop这样的方案应运而生 请描述event loop（事件循环/事件轮询）的机制，可画图因为js是单线程运行的，所以异步要基于回调来实现，而event loop就是异步回调的实现原理 JS先把同步代码执行完再去执行异步代码，如果某一行执行报错，则停止下面代码的执行。 通过例">
<meta name="keywords" content="Javascript">
<meta property="og:type" content="article">
<meta property="og:title" content="javascript异步进阶">
<meta property="og:url" content="elfeach.gitee.io/2020/10/27/javascript异步进阶/index.html">
<meta property="og:site_name" content="Elfecho’Blog">
<meta property="og:description" content="为什么要有Event Loop？因为Javascript设计之初就是一门单线程语言，因此为了实现主线程的不阻塞，Event Loop这样的方案应运而生 请描述event loop（事件循环/事件轮询）的机制，可画图因为js是单线程运行的，所以异步要基于回调来实现，而event loop就是异步回调的实现原理 JS先把同步代码执行完再去执行异步代码，如果某一行执行报错，则停止下面代码的执行。 通过例">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://i.loli.net/2020/10/28/NqGzZJ9Osn52jcA.gif">
<meta property="og:image" content="https://i.loli.net/2020/10/28/6tUvEqGumias57J.png">
<meta property="og:image" content="https://i.loli.net/2020/10/28/OESNXk3yvHzlDQn.png">
<meta property="og:image" content="https://i.loli.net/2020/10/28/xaYT2IHJDqNioBm.png">
<meta property="og:image" content="https://i.loli.net/2020/10/28/1PhNZ7uqLUzMVfO.png">
<meta property="og:image" content="https://i.loli.net/2020/10/29/kc6giZCOj1H4ANW.png">
<meta property="og:image" content="https://i.loli.net/2020/10/29/lTON742xKtmiS8G.png">
<meta property="og:updated_time" content="2020-10-29T13:56:21.084Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="javascript异步进阶">
<meta name="twitter:description" content="为什么要有Event Loop？因为Javascript设计之初就是一门单线程语言，因此为了实现主线程的不阻塞，Event Loop这样的方案应运而生 请描述event loop（事件循环/事件轮询）的机制，可画图因为js是单线程运行的，所以异步要基于回调来实现，而event loop就是异步回调的实现原理 JS先把同步代码执行完再去执行异步代码，如果某一行执行报错，则停止下面代码的执行。 通过例">
<meta name="twitter:image" content="https://i.loli.net/2020/10/28/NqGzZJ9Osn52jcA.gif">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"没有找到与[${query}]相关的内容","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="elfeach.gitee.io/2020/10/27/javascript异步进阶/">





  <title>javascript异步进阶 | Elfecho’Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c491056d7021e5c248129f6222a89004";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  <script type="text/javascript" src="/js/src/crash_cheat.js"></script>
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Elfecho’Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">有空时来歇歇脚吧</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="elfeach.gitee.io/2020/10/27/javascript异步进阶/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="elfecho">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Elfecho’Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">javascript异步进阶</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-27T21:00:59+08:00">
                2020-10-27
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            
            
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.6k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  18 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="为什么要有Event-Loop？"><a href="#为什么要有Event-Loop？" class="headerlink" title="为什么要有Event Loop？"></a>为什么要有Event Loop？</h1><p>因为Javascript设计之初就是一门单线程语言，因此为了实现主线程的不阻塞，<strong>Event Loop</strong>这样的方案应运而生</p>
<h1 id="请描述event-loop（事件循环-事件轮询）的机制，可画图"><a href="#请描述event-loop（事件循环-事件轮询）的机制，可画图" class="headerlink" title="请描述event loop（事件循环/事件轮询）的机制，可画图"></a>请描述event loop（事件循环/事件轮询）的机制，可画图</h1><p>因为js是单线程运行的，所以异步要基于回调来实现，而event loop就是异步回调的实现原理</p>
<p>JS先把同步代码执行完再去执行异步代码，如果某一行执行报错，则停止下面代码的执行。</p>
<p>通过例子来讲event loop机制</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">"Hi"</span>);</span><br><span class="line">setTimeout(<span class="function"><span class="keyword">function</span> <span class="title">cb1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"cb1"</span>); <span class="comment">// cb即callback</span></span><br><span class="line">&#125;, <span class="number">5000</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"Bye"</span>);</span><br></pre></td></tr></table></figure>
<p>运行大致过程如下（本例子缺少了微任务队列，所以下图没有显示微任务队列）</p>
<p><img src="https://i.loli.net/2020/10/28/NqGzZJ9Osn52jcA.gif" alt="测试12"></p>
<p>显示的Web APIs只有宏任务，异步任务分为宏任务和微任务。</p>
<blockquote>
<p>1.同步代码（栈里面的代码）顺序执行，遇到异步代码就记录一下，在此过程中异步代码如果是宏任务移动到Web APIs，直到定时的时间到就放入宏任务队列，即图中的Callback Queue。</p>
<p>如果是微任务则放入微任务队列（本例子没有微任务），不会经过Web APIs。如果同步代码执行完，调用栈call stack为空，去查看微任务队列，每执行完一个微任务，它就会从微任务队列出队，直到微任务队列微空后，尝试DOM渲染（如果DOM结构发生变化）。</p>
<p>2.然后Event Loop开始工作，然后轮询查找宏任务队列Callback Queue，如有则移动到Call Stack执行…</p>
<p>3.每执行完一个宏任务，就会去检查微任务队列，若微任务队列有，就执行到微任务为空，再尝试DOM渲染，然后去看宏任务队列，继续轮询查找（永动机一样不停地重复操作）。</p>
</blockquote>
<blockquote>
<p>注意：</p>
<p>1.这里的Web APIs就是处理定时或者异步API的。</p>
<p>2.微任务是ES6语法规定的，宏任务是由浏览器规定的。</p>
<p>3.<strong>执行的顺序是 <code>执行栈中的代码 =&gt; 微任务 =&gt; 宏任务（后面会展开讲）</code></strong></p>
</blockquote>
<p>如果是用户手动触发时</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"Hi"</span>);</span></span><br><span class="line"><span class="javascript">    $(<span class="string">"#btn1"</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">    	<span class="built_in">console</span>.log(<span class="string">"button clicked"</span>);</span></span><br><span class="line"><span class="undefined">    &#125;)</span></span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"Bye"</span>);</span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>这个和上面的例子几乎一样，只不过回调函数放在Web APIs，点击按钮的时候回调函数就放在Callback Queue。从这里可以看出DOM事件的触发也是基于event loop的。</p>
<h1 id="promise有哪三种状态？如何变化？"><a href="#promise有哪三种状态？如何变化？" class="headerlink" title="promise有哪三种状态？如何变化？"></a>promise有哪三种状态？如何变化？</h1><p>Promise三种状态：pending、fulfilled、rejected</p>
<p><strong>状态变化：</strong></p>
<ol>
<li><p>pending–&gt;fulfilled(成功了)  </p>
</li>
<li><p>pending–&gt;rejected(失败了)</p>
</li>
</ol>
<p>状态变化是不可逆的</p>
<p><strong>状态的表现</strong></p>
<ol>
<li><p>pending状态不会触发then和catch</p>
</li>
<li><p>fulfilled状态的Promise会触发后续的then回调函数</p>
</li>
<li><p>rejected状态的Promise会触发后续的catch回调函数</p>
</li>
</ol>
<p><strong>then和catch改变状态</strong></p>
<p>then正常返回resolved，里面有报错则返回rejected的Promise对象</p>
<p>catch正常返回resolved，里面有报错则返回rejected的Promise对象</p>
<p><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject" target="_blank" rel="noopener"><code>Promise.reject(reason)</code></a>返回一个状态为失败的Promise对象，并将给定的失败信息传递给对应的处理方法catch</p>
<p><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve" target="_blank" rel="noopener"><code>Promise.resolve(value)</code></a>返回一个状态为成功的Promise对象，并将成功信息传递给对应方法then</p>
<p>Promise.resolve(obj)：从一个thenable或一个值创建一个新的promise</p>
<p>Promise.reject(err)：创建一个被拒绝的promise，err作为原因</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p1 = <span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">100</span>;</span><br><span class="line">&#125;) <span class="comment">//Promise.resolve()返回fulfilled状态的Promise对象，然后then执行完不报错，还是返回一个fulfilled状态的Promise</span></span><br><span class="line"><span class="comment">// console.log('p1', p1); // resolve触发后续的 then 回调</span></span><br><span class="line"> </span><br><span class="line">p1.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123; <span class="comment">// 传进来p1返回的100，但是没有使用，打印123</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"123"</span>); <span class="comment">// 打印 100</span></span><br><span class="line">&#125;)</span><br><span class="line"> </span><br><span class="line"><span class="keyword">const</span> p2 = <span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"then error"</span>);</span><br><span class="line">&#125;) <span class="comment">//Promise.resolve()返回fulfilled状态的Promise对象，然后then执行完报错了！返回一个rejected状态的Promise</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">// console.log('p2', p2); // rejected触发后续的 catch 回调</span></span><br><span class="line">p2.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'456'</span>);</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">err</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.error(<span class="string">'err100'</span>, err); <span class="comment">// 打印 err100 Error: then error at &lt;anonymous&gt;</span></span><br><span class="line">&#125;) <span class="comment">// rejected状态的Promise后续会触发catch而不是then</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p3 = <span class="built_in">Promise</span>.reject(<span class="string">"my error"</span>).catch(<span class="function"><span class="params">err</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.error(err);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'p3'</span>, p3);</span><br><span class="line">p3.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">100</span>);</span><br><span class="line">&#125;)</span><br><span class="line"> </span><br><span class="line"><span class="keyword">const</span> p4 = <span class="built_in">Promise</span>.reject(<span class="string">'my error'</span>).catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"catch err"</span>);</span><br><span class="line">&#125;)</span><br><span class="line"> </span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'p4'</span>, p4);</span><br><span class="line">p4.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">200</span>);</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.error(<span class="string">"some err"</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2020/10/28/6tUvEqGumias57J.png" alt="image-20201028203456689"></p>
<h2 id="promise练习题"><a href="#promise练习题" class="headerlink" title="promise练习题"></a>promise练习题</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">1</span>);</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">2</span>);</span><br><span class="line">&#125;).then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">3</span>);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 1  3</span></span><br></pre></td></tr></table></figure>
<p>解释：Promise.resolve()返回一个resolved状态的Promise后续触发then回调，然后打印1，then执行完返回resolved状态的Promise，然后再执行then，打印3，返回返回resolved状态的Promise。因为没Error，没有rejected状态的Promise，所以不会触发catch回调。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span>=&gt;</span>&#123; <span class="comment">// rejected</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'erro1'</span>);</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">2</span>);</span><br><span class="line">&#125;).then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">3</span>);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 1 2 3</span></span><br></pre></td></tr></table></figure>
<p>解析： 与上例的不同就是多了throw new Error(‘erro1’);</p>
<p>Promise.resolve()返回一个resolved状态的Promise后续触发then回调，然后打印1，执行throw new Error(‘erro1’);返回一个rejected状态的Promise，触发catch回调函数，打印2，接着返回resolved状态的Promise，触发后面then的回调，打印3，返回一个resolved状态的Promise。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'erro1'</span>);</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">2</span>);</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">3</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>解释：这个和上题的不同就是最后一个回调是catch的，不是then的回调。</p>
<p>理由和上面一模一样，不用多解释，只不过打印2之后返回的是fulfilled状态的Promise，后面没有then，所以不打印3。catch里面只要没报错Error，那么就是resolved状态的Promise。</p>
<p><strong>我个人觉得需要额外注意的点</strong>：大家不要忽略最后的返回值，返回值会链式传递给下一个回调，只不过我们这里的例子没有强调返回值，等于return undefined；如果then/catch回调函数有形参，而上一个回调函数有返回值，那么返回值会作为下一个回调的形参。</p>
<h1 id="async-await"><a href="#async-await" class="headerlink" title="async/await"></a>async/await</h1><p>因为之前异步回调callback hell 的问题，所以ES6就出了Promise的then/catch的链式调用，但还是基于回调函数，所以ES7就出了async/await，用同步语法彻底消灭回调函数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">loadImg</span>(<span class="params">src</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(</span><br><span class="line">      (resolve, reject) =&gt; &#123;</span><br><span class="line">          <span class="keyword">const</span> img = <span class="built_in">document</span>.createElement(<span class="string">'img'</span>)</span><br><span class="line">          img.onload = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">              resolve(img)</span><br><span class="line">          &#125;</span><br><span class="line">          img.onerror = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">              <span class="keyword">const</span> err = <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">`图片加载失败<span class="subst">$&#123;src&#125;</span>`</span>)</span><br><span class="line">              reject(err)</span><br><span class="line">          &#125;</span><br><span class="line">          img.src = src</span><br><span class="line">      &#125;</span><br><span class="line">  )</span><br><span class="line">  <span class="keyword">return</span> p</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> url1 = <span class="string">'https://elfeach.gitee.io/blog/images/avatar.jpg'</span></span><br><span class="line"><span class="keyword">let</span> url2 = <span class="string">'https://www.wdku.net/public/ico/ocr/logo.png'</span></span><br><span class="line">loadImg(url1).then(<span class="function"><span class="params">img1</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(img1.width)</span><br><span class="line">  <span class="keyword">return</span> img1</span><br><span class="line">&#125;).then(<span class="function"><span class="params">img1</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(img1.height)</span><br><span class="line">  <span class="keyword">return</span> loadImg(url2)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">img2</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(img2.width)</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">err</span> =&gt;</span> <span class="built_in">console</span>.error(err))</span><br><span class="line"></span><br><span class="line"><span class="comment">// ================上面用Promise也是不断的处理回调=================</span></span><br><span class="line"><span class="comment">// 立即执行函数前面有个!，是为了避免和上面最后一句不写分号导致当成函数的冲突</span></span><br><span class="line"></span><br><span class="line">!(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// img1</span></span><br><span class="line">  <span class="keyword">const</span> img1 = <span class="keyword">await</span> loadImg(url1)</span><br><span class="line">  <span class="built_in">console</span>.log(img1.width, img1.height)</span><br><span class="line">  <span class="comment">// img2</span></span><br><span class="line">  <span class="keyword">const</span> img2 = <span class="keyword">await</span> loadImg(url2)</span><br><span class="line">  <span class="built_in">console</span>.log(img2.width, img2.height)</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p>await后面可以跟Promise对象或者async函数执行</p>
<p>额外提示：立即执行函数前面有个!，是为了避免和上面最后一句不写分号导致当成函数的冲突，比如下面的例子”abc”没有分号，就把它当成了一个函数，因为后面跟着”abc”(…)()，alert换行后跟着括号还是认为是函数。你会发现平时引入js文件的时候，前面可能很多都有!就是这个原因</p>
<p><img src="https://i.loli.net/2020/10/28/OESNXk3yvHzlDQn.png" alt="20200705165232283"></p>
<h1 id="async-await和Promise的关系"><a href="#async-await和Promise的关系" class="headerlink" title="async/await和Promise的关系"></a>async/await和Promise的关系</h1><blockquote>
<ol>
<li><p>执行async函数，返回的是Promise对象</p>
</li>
<li><p>await相当于Promise的then</p>
</li>
<li><p>try…catch可捕获异常，代替了Promise的catch</p>
</li>
</ol>
</blockquote>
<h2 id="执行async函数，返回的是Promise对象"><a href="#执行async函数，返回的是Promise对象" class="headerlink" title="执行async函数，返回的是Promise对象"></a>执行async函数，返回的是Promise对象</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">fn1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">100</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> res1 = fn1() <span class="comment">// 执行async函数，返回的是一个Promise对象</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'res1'</span>, res1)</span><br><span class="line">res1.then(<span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'data'</span>, data)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2020/10/28/xaYT2IHJDqNioBm.png" alt="image-20201028222359155"></p>
<h2 id="await相当于Promise的then"><a href="#await相当于Promise的then" class="headerlink" title="await相当于Promise的then"></a>await相当于Promise的then</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">!(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> p1 = <span class="built_in">Promise</span>.resolve(<span class="number">300</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(p1);</span><br><span class="line">    <span class="keyword">const</span> data = <span class="keyword">await</span> p1; <span class="comment">// 这里await后面的语句相当于Promise的then里面的回调函数</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'data'</span>, data); <span class="comment">// data 300</span></span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p>这里可以看出await后面跟着一个Promise，而执行了这一行之后，相当触发了于Promise.then回调，拿到了300的值最后打印</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">fn1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(<span class="number">100</span>);</span><br><span class="line">&#125;</span><br><span class="line">!(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> data2 = <span class="keyword">await</span> fn1(); <span class="comment">// await后面相当于跟了一个promise函数</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'data2'</span>, data2); <span class="comment">// data2 100</span></span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p>这里需要说明一下，这里await后面跟着一个Promise对象，执行这一行相当于Promise.then回调，而且await这一行不执行完毕是不会去执行后面的语句。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">!(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> data3 = <span class="keyword">await</span> <span class="number">400</span>; <span class="comment">// 若后面不是Promise对象，则直接返回表达式执行结果，这里是400</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'data3'</span>, data3); <span class="comment">// data3 400</span></span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p>若await后面不是Promise对象，比如字符串、函数、数字，则直接返回该表达式执行结果，这里是400</p>
<h2 id="try…catch可捕获异常，代替了Promise的catch"><a href="#try…catch可捕获异常，代替了Promise的catch" class="headerlink" title="try…catch可捕获异常，代替了Promise的catch"></a>try…catch可捕获异常，代替了Promise的catch</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">!(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> p4 = <span class="built_in">Promise</span>.reject(<span class="string">'err1'</span>); <span class="comment">// rejected 状态</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> res = <span class="keyword">await</span> p4;</span><br><span class="line">        <span class="built_in">console</span>.log(res);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (ex) &#123;</span><br><span class="line">        <span class="built_in">console</span>.error(ex); <span class="comment">// try...catch相当于Promise的catch</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p>这里的try…catch相当于Promise的catch</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">!(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> p4 = <span class="built_in">Promise</span>.reject(<span class="string">'err1'</span>);</span><br><span class="line">    <span class="keyword">const</span> res = <span class="keyword">await</span> p4; <span class="comment">// await后面的语句相当于then里面的回调,但是这里需要catch，这里会报错，后面不会执行</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'res'</span>, res);</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p>可以看到这里并没有打印res，并没有执行后面一句console.log，如果要解决这个问题，那么就需要try…catch执行catch中的逻辑，就像上一个例子。</p>
<blockquote>
<p>综上所述</p>
<p>如果await等待的是一个Promise对象，那么它只想等fulfilled状态的Promise，后续的语句相当与then回调才会执行</p>
<p>如果等来的是rejected状态的Promise，await接不住，必须try…catch，在catch中接住它，然后可以进行一定的自定义说明。</p>
</blockquote>
<h1 id="async-function的函数"><a href="#async-function的函数" class="headerlink" title="async function的函数"></a>async function的函数</h1><p>返回结果都是 Promise 对象（如果函数内没返回 Promise ，则自动封装一下）</p>
<h1 id="async-表达式"><a href="#async-表达式" class="headerlink" title="async+表达式"></a>async+表达式</h1><p>await 后面跟 Promise 对象：会阻断后续代码，等待状态变为 fulfilled ，才获取结果并继续执行<br>await 后续跟非 Promise 对象：会直接返回</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">()</span> =&gt;</span> &#123;&#125;)</span><br><span class="line">    <span class="keyword">await</span> p1</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'p1'</span>) <span class="comment">// 不会执行</span></span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2020/10/28/1PhNZ7uqLUzMVfO.png" alt="image-20201028231244313"></p>
<p>这里的Promise里面没有resolve(), 导致await后面的表达式得不到结果，而await后面的语句都相当于Promise的then回调，只要await这里不执行，那么后面所有的callback都不会执行，所以不会打印”p1”</p>
<h1 id="关于异步独立知识点"><a href="#关于异步独立知识点" class="headerlink" title="关于异步独立知识点"></a>关于异步独立知识点</h1><p>做个简单的乘法异步方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">muti</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            resolve(num * num);</span><br><span class="line">        &#125;, <span class="number">1000</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"> </span><br><span class="line">nums.forEach(<span class="keyword">async</span> (i) =&gt;&#123;</span><br><span class="line">    <span class="keyword">const</span> res = <span class="keyword">await</span> muti(i);</span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>由于forEach循环是同步的执行方法，循环3次已经结束了，1s的时间其实是3次循环执行到await这里卡住了，await后面的语句相当于callback，await这里不执行完是不会执行后面的，之后3次循环的await几乎同时结束，瞬间打印出1，4，9</p>
<p>那么如果想要每隔1s执行异步循环的话用for…of</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">muti</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            resolve(num * num);</span><br><span class="line">        &#125;, <span class="number">1000</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">!(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i <span class="keyword">of</span> nums) &#123;</span><br><span class="line">        <span class="keyword">let</span> res = <span class="keyword">await</span> muti(i)</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<h1 id="微任务与宏任务"><a href="#微任务与宏任务" class="headerlink" title="微任务与宏任务"></a>微任务与宏任务</h1><blockquote>
<p>宏任务：setTimeout、setInterval、Ajax、<code>I/O</code>、<code>UI交互事件(比如DOM事件)</code></p>
<p>微任务：Promise回调、async/await、<code>process.nextTick(</code>Node独有，注册函数的优先级比Promise回调函数要高<code>)</code>、<code>MutaionObserver</code></p>
<p>微任务执行时机比宏任务要早（记住）</p>
<p>注意：script全部代码、<strong>(这个是执行栈的代码，属于同步代码)，包括new Promise（function(){…}）里面的代码，只有then、catch回调才是微任务</strong></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="number">100</span>);      <span class="comment">// 1</span></span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">200</span>);  <span class="comment">// 4</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 微任务</span></span><br><span class="line"><span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">300</span>);  <span class="comment">// 3</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">400</span>); 	   <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<h1 id="宏任务和微任务以及Promise状态变化的思考"><a href="#宏任务和微任务以及Promise状态变化的思考" class="headerlink" title="宏任务和微任务以及Promise状态变化的思考"></a>宏任务和微任务以及Promise状态<fulfilled><rejected>变化的思考</rejected></fulfilled></h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">let</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="string">"fulfilled"</span>);</span><br><span class="line">    reject(<span class="string">"rejected"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">let</span> p2 = p1.then(<span class="function"><span class="params">value</span> =&gt;</span> <span class="built_in">console</span>.log(value))</span><br><span class="line">.catch(<span class="function"><span class="params">reason</span> =&gt;</span> <span class="built_in">console</span>.log(reason));</span><br><span class="line"> </span><br><span class="line"><span class="built_in">console</span>.log(p1);</span><br><span class="line"><span class="built_in">console</span>.log(p2);</span><br></pre></td></tr></table></figure>
<p>打印的时候，p1的new Promise(…)里面是同步代码，打印出来的状态是<fulfilled>，p2的执行需要加入微任务队列，然后继续执行后面的同步代码，打印此时p1、p2的状态分别为<fulfilled>和<pending>。因为打印的时候p2的状态是不确定的【可能是fulfilled也可能rejected，取决于后面是触发了resolve()还是reject()】，因为微任务还没有执行，执行后p2的状态就确定了。</pending></fulfilled></fulfilled></p>
<p><strong>Promise的状态改变是单向不可逆不可撤销的，resolve()执行就是<fulfilled>状态，后面再跟一个reject()也不会有效果</fulfilled></strong>，因为任务触发放在微任务队列了，resolve()和reject()一般我们会放在if-else两种逻辑情况里面。这里是resolve()在前，返回<fulfilled>状态的Promise，如果是reject()在前，那么返回<rejected>状态的对象，大家可以去试一下。</rejected></fulfilled></p>
<p>如果换一种写法，把打印p1、p2的逻辑放在微任务执行之后呢</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="string">"fulfilled"</span>);</span><br><span class="line">    reject(<span class="string">"rejected"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">let</span> p2 = p1.then(<span class="function"><span class="params">value</span> =&gt;</span> <span class="built_in">console</span>.log(value))</span><br><span class="line">.catch(<span class="function"><span class="params">reason</span> =&gt;</span> <span class="built_in">console</span>.log(reason));</span><br><span class="line"> </span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(p1);</span><br><span class="line">    <span class="built_in">console</span>.log(p2);</span><br><span class="line">&#125;, <span class="number">0</span>)</span><br></pre></td></tr></table></figure>
<p>这样就可以看到p2也成了<fulfilled>状态，中间微任务执行完js引擎工作结束返回了3，这个随机值不同浏览器每次执行返回不同，不用管这个</fulfilled></p>
<blockquote>
<p>总结：</p>
<p>如果是new Promise，函数里面是同步代码，会返回一个确定的结果，比如这里的p1是<fulfilled>状态的Promise</fulfilled></p>
<p>如果一个Promise里面的代码需要放在微任务执行，而此时同步代码没执行完，那么打印此时的Promise是一个<pending>状态</pending></p>
<p>如果微任务执行完，那么Promise对象的状态就确定了，不会出现<pending>，只有resolve()——<fulfilled>和reject()——<rejected>这两种确定的状态。</rejected></fulfilled></pending></p>
<p><strong>Promise的状态改变是单向不可逆不可撤销的，resolve()执行最后会是<fulfilled>状态，后面再跟一个reject()也不会变成<rejected>状态</rejected></fulfilled></strong></p>
</blockquote>
<h1 id="Event-loop-和DOM渲染"><a href="#Event-loop-和DOM渲染" class="headerlink" title="Event loop 和DOM渲染"></a>Event loop 和DOM渲染</h1><ul>
<li>JS是单线程的，而且和DOM渲染共用一个线程</li>
<li>JS执行的时候，得留一些时机供DOM渲染</li>
</ul>
<h1 id="为什么微任务执行时机比宏任务早？"><a href="#为什么微任务执行时机比宏任务早？" class="headerlink" title="为什么微任务执行时机比宏任务早？"></a>为什么微任务执行时机比宏任务早？</h1><p>宏任务：DOM渲染后触发，如setTimeout</p>
<p>微任务：DOM渲染前触发，如Promise</p>
<p><strong>为什么微任务在渲染前，宏任务在渲染后？</strong></p>
<p>- 微任务：ES 语法标准之内，JS 引擎来统一处理。即不用浏览器有任何干预，可一次性处理完，更快更及时。<br>- 宏任务：ES 语法没有，JS 引擎不处理，浏览器（或 nodejs）干预处理。</p>
<p>综上所述，代码执行顺序如下：</p>
<blockquote>
<p>1.call Stack清空，即同步任务执行完（执行栈内的代码，执行完弹栈清空）</p>
<p>2.执行当前的微任务队列的任务</p>
<p>3.尝试DOM渲染（如果DOM结构有改变则重新渲染）</p>
<p>4.触发Event Loop，执行宏任务队列的任务</p>
<p>5.每执行一个宏任务会回到步骤2，检查执行微任务，依次轮询。</p>
</blockquote>
<h2 id="小试牛刀1（过程梳理）"><a href="#小试牛刀1（过程梳理）" class="headerlink" title="小试牛刀1（过程梳理）"></a>小试牛刀1（过程梳理）</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'timeout1'</span>)</span><br><span class="line">    <span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'promise1'</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'promise2'</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;, <span class="number">100</span>)</span><br><span class="line"> </span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'timeout2'</span>)</span><br><span class="line">    <span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'promise3'</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;, <span class="number">200</span>)</span><br></pre></td></tr></table></figure>
<blockquote>
<ol>
<li>先将两个<code>setTimeout</code>塞到宏任务队列中</li>
<li>当第一个<code>setTimeout1</code>时间到了执行的时候，首先打印timeout1，然后在微任务队列中塞入<code>promise1</code>和<code>promise2</code></li>
<li>当第一个<code>setTimeout1</code>执行完毕后，会去微任务队列检查发现有两个<code>promise</code>，会把两个<code>promise</code>按顺序执行完</li>
<li>尝试DOM渲染</li>
<li>执行下一个宏任务，两个<code>promise</code>执行完毕后会微任务队列中没有任务了，会去宏任务中执行下一个任务 <code>setTimeout2</code></li>
<li>当<code>setTimeout2</code> 执行的时候，先打印一个timeout2，然后又在微任务队列中塞了一个<code>promise3</code></li>
<li>当<code>setTimeout2</code>执行完毕后会去微任务队列检查，发现有一个promise3，会将<code>promise3</code>执行</li>
<li>会依次打印 <code>timeout1 promise1 promise2 timeout2 promise3</code></li>
</ol>
</blockquote>
<p>注意：当setTimeout定时时间间隔一样的时候，旧版本的node可能与浏览器端的运行结果不一样。 </p>
<p>高手想挑战更多，请见这篇文章：<a href="https://juejin.im/post/5a6155126fb9a01cb64edb45" target="_blank" rel="noopener">Event Loop的规范和实现</a></p>
<h2 id="小试牛刀2（字节烂大街的笔试题，浏览器不同，结果还真不同）"><a href="#小试牛刀2（字节烂大街的笔试题，浏览器不同，结果还真不同）" class="headerlink" title="小试牛刀2（字节烂大街的笔试题，浏览器不同，结果还真不同）"></a>小试牛刀2（字节烂大街的笔试题，浏览器不同，结果还真不同）</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">async1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'async1 start'</span>);</span><br><span class="line">    <span class="keyword">await</span> async2();</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'async1 end'</span>);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">async2</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'async2'</span>);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'script start'</span>);</span><br><span class="line"> </span><br><span class="line">setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'setTimeout'</span>);</span><br><span class="line">&#125;, <span class="number">0</span>)</span><br><span class="line"> </span><br><span class="line">async1();</span><br><span class="line"> </span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'promise1'</span>);</span><br><span class="line">    resolve();</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"???"</span>); <span class="comment">// 这一句是我自己加的，目的考察大家是否知道同步代码和微任务，迷惑大家resolve()后面是否还会执行</span></span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'promise2'</span>);</span><br><span class="line">&#125;)</span><br><span class="line"> </span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'script end'</span>);</span><br></pre></td></tr></table></figure>
<blockquote>
<ol>
<li>从上到下，先是2个函数定义</li>
<li>再打印一个script start</li>
<li>看到setTimeout，里面回调函数放入宏任务队列等待执行</li>
<li>接着执行async1()，打印async1 start，看到await async2()，执行后打印async2，await后面的语句相当于Promise的then回调函数，所以是微任务，console.log(‘async1 end’)放入微任务队列</li>
<li>执行new Promise，new Promise里面传的函数是同步代码，打印promise1，执行resolve()，后续触发的then回调是微任务，放入微任务队列，然后执行同步代码打印 ???</li>
<li>打印script end，同步代码执行完了</li>
<li>检查微任务队列，依次打印async1 end和promise2（这里指的是chrome/73+浏览器，后面会说不同）</li>
<li>尝试DOM渲染（如果DOM结构有变化）</li>
<li>检查宏任务队列，打印setTimeout</li>
<li>检查微任务队列为空，尝试DOM渲染，检查宏任务队列为空，执行结束</li>
</ol>
</blockquote>
<p>综上，打印结果如下，chrome/73+的浏览器结果</p>
<p><img src="https://i.loli.net/2020/10/29/kc6giZCOj1H4ANW.png" alt="image-20201029214139935"></p>
<p>chrome73之前的版本和我目前Safari/605.1.15版本打印依次为</p>
<p><img src="https://i.loli.net/2020/10/29/lTON742xKtmiS8G.png" alt="image-20201029214508625"></p>
<p>chrome/73 之前的版本，await后面的代码，都是等微任务执行完才执行后面的部分，相当于放在微任务的末尾。</p>
<p>chrome/73+后的版本，如果await一个常量或者async函数或者普通函数，都会把后面紧接着的代码正常添加到微任务队列。</p>
<p><strong>为什么这里有返回undefined之后才会打印setTimeout</strong>，因为前面是同步代码和微任务执行完了，JS引擎工作结束，开始返回值。后面打印的setTimeout是浏览器处理的。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Javascript/" rel="tag"># Javascript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/10/26/React脚手架搭建/" rel="next" title="React脚手架搭建">
                <i class="fa fa-chevron-left"></i> React脚手架搭建
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/10/28/浏览器的回流与重绘/" rel="prev" title="浏览器的回流与重绘">
                浏览器的回流与重绘 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="elfecho">
            
              <p class="site-author-name" itemprop="name">elfecho</p>
              <p class="site-description motion-element" itemprop="description">擅长各项前端技能，深入研究移动端开发与前端性能。非专业视觉设计师。此为博客一枚。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://elfeach.gitee.io/resume/" title="个人主页" target="_blank">个人主页</a>
                  </li>
                
              </ul>
            </div>
          
          <!-- 网易云音乐 
          <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=31421442&auto=1&height=66"></iframe> -->

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#为什么要有Event-Loop？"><span class="nav-number">1.</span> <span class="nav-text">为什么要有Event Loop？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#请描述event-loop（事件循环-事件轮询）的机制，可画图"><span class="nav-number">2.</span> <span class="nav-text">请描述event loop（事件循环/事件轮询）的机制，可画图</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#promise有哪三种状态？如何变化？"><span class="nav-number">3.</span> <span class="nav-text">promise有哪三种状态？如何变化？</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#promise练习题"><span class="nav-number">3.1.</span> <span class="nav-text">promise练习题</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#async-await"><span class="nav-number">4.</span> <span class="nav-text">async/await</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#async-await和Promise的关系"><span class="nav-number">5.</span> <span class="nav-text">async/await和Promise的关系</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#执行async函数，返回的是Promise对象"><span class="nav-number">5.1.</span> <span class="nav-text">执行async函数，返回的是Promise对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#await相当于Promise的then"><span class="nav-number">5.2.</span> <span class="nav-text">await相当于Promise的then</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#try…catch可捕获异常，代替了Promise的catch"><span class="nav-number">5.3.</span> <span class="nav-text">try…catch可捕获异常，代替了Promise的catch</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#async-function的函数"><span class="nav-number">6.</span> <span class="nav-text">async function的函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#async-表达式"><span class="nav-number">7.</span> <span class="nav-text">async+表达式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#关于异步独立知识点"><span class="nav-number">8.</span> <span class="nav-text">关于异步独立知识点</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#微任务与宏任务"><span class="nav-number">9.</span> <span class="nav-text">微任务与宏任务</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#宏任务和微任务以及Promise状态变化的思考"><span class="nav-number">10.</span> <span class="nav-text">宏任务和微任务以及Promise状态变化的思考</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Event-loop-和DOM渲染"><span class="nav-number">11.</span> <span class="nav-text">Event loop 和DOM渲染</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#为什么微任务执行时机比宏任务早？"><span class="nav-number">12.</span> <span class="nav-text">为什么微任务执行时机比宏任务早？</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#小试牛刀1（过程梳理）"><span class="nav-number">12.1.</span> <span class="nav-text">小试牛刀1（过程梳理）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小试牛刀2（字节烂大街的笔试题，浏览器不同，结果还真不同）"><span class="nav-number">12.2.</span> <span class="nav-text">小试牛刀2（字节烂大街的笔试题，浏览器不同，结果还真不同）</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">elfecho</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">39.6k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
